package com.roundarch.www.ui;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.roundarch.www.model.Authorities;
import com.roundarch.www.model.Files;
import com.roundarch.www.model.User;
import com.roundarch.www.model.UserDetail;
import com.roundarch.www.util.StringUtils;
import com.roundarch.www.util.propertyeditor.EntityPropertyEditor;

@Controller
@RequestMapping("/users")
public class UserController extends AbstractEntityController<User> {

	private final Log logger = LogFactory.getLog(getEntityClass());

	

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(
			@Valid @ModelAttribute("entity") User entity,
			BindingResult result,
			Model model,
			@RequestParam(value = "saveTarget", defaultValue = "show") String saveTarget,
			HttpServletRequest request) {

		if (result.hasErrors()) {
			// TODO set 'flash' to error
			buildEditModel(entity, model,request);
			return StringUtils.joinPath(getRootRequestMapping(), "edit");
		}

		try {
			if (entity.isNew()) {
				entity.setPassword(getEncryptedPassword(entity.getPassword()));
			}
			getEntityService().save(entity);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:" + buildSaveTargetUrl(saveTarget, entity);
	}

	@ModelAttribute("entity")
	public User entity(HttpServletRequest request) {
		String id = request.getParameter("id");
		if (StringUtils.isNotBlank(id))
			return getEntityService()
					.find(Long.parseLong(id), getEntityClass());

		User user = BeanUtils.instantiateClass(getEntityClass());
		user.setUserDetail(new UserDetail());
		user.setAuthorities(new Authorities());
		return user;
	}

	

	@Override
	protected void buildEditModel(User entity, Model model, HttpServletRequest request) {
		super.buildEditModel(entity, model,request);
		model.addAttribute("authorities",
				getEntityService().listAll(Authorities.class));
	}

	@Override
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		super.initBinder(binder);

		binder.registerCustomEditor(Authorities.class,
				new EntityPropertyEditor<Authorities>(getEntityService(),
						Authorities.class));
	}

	private String getEncryptedPassword(String password) {
		String encryptedPassword = null;

		MessageDigest messageDigest;
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.update(password.getBytes(), 0, password.length());
			String hashedPass = new BigInteger(1, messageDigest.digest())
					.toString(16);
			if (hashedPass.length() < 32) {
				hashedPass = "0" + hashedPass;
			}
			encryptedPassword = hashedPass;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		return encryptedPassword;
	}
}
